package com.wobito.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wobito.common.constants.BaseResponse;
import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.constants.TableDataInfo;
import com.wobito.common.utils.ResultUtils;
import com.wobito.pojo.bean.Book;
import com.wobito.pojo.dto.book.BookDTO;
import com.wobito.pojo.enums.BookStatusEnum;
import com.wobito.pojo.enums.IsDeletedEnum;
import com.wobito.pojo.vo.book.AddBookVO;
import com.wobito.pojo.vo.book.BookVO;
import com.wobito.pojo.vo.book.UpdateBookVO;
import com.wobito.service.BookService;
import com.wobito.service.IBorrowReturnLogService;
import com.wobito.system.aspect.OperLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Wangbaba
 * @Date 2024/7/1 10:10
 * @Version 1.0
 */
@RestController
@RequestMapping("/manage/bookManage")
@Api(tags = "书籍管理")
public class BookManageController {

    @Autowired
    private BookService bookService;
    @Autowired
    private IBorrowReturnLogService borrowReturnLogService;

    @GetMapping()
    @ApiOperation(value = "条件查询书籍")
    @OperLog(thing = "条件查询书籍")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getBookList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "cabinetId", required = false) Long cabinetId,
                                    @RequestParam(value = "queryName", required = false) String queryName,
                                    @RequestParam(value = "state", required = false) Integer state,
                                    @RequestParam(value = "isDeleted", required = false) Integer isDeleted) {
        TableDataInfo dataInfo = new TableDataInfo();
        PageHelper.startPage(pageNum, pageSize);
        List<BookDTO> bookDTOS = bookService.selectBookList(new BookVO(cabinetId, queryName, state, isDeleted));
        dataInfo.setRows(bookDTOS);
        dataInfo.setTotal(new PageInfo(bookDTOS).getTotal());
        return ResultUtils.success(dataInfo);
    }

    @GetMapping("/getBorrowByBook/{id}")
    @ApiOperation(value = "根据书籍ID查询借阅日志")
    @OperLog(thing = "根据书籍ID查询借阅日志")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getBorrowByBook(@PathVariable("id") Long id) {
        return ResultUtils.success(borrowReturnLogService.selectBookBorrowByBookId(id));
    }

    @PutMapping()
    @ApiOperation(value = "添加书籍")
    @OperLog(thing = "添加书籍")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse addBook(@Valid @RequestBody AddBookVO addBookVO) {
        Book book = bookService.getOne(new LambdaQueryWrapper<Book>().eq(Book::getRfid, addBookVO.getRfid()));
        if (ObjectUtil.isNotEmpty(book)) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "此RFID已被绑定");
        }
        return ResultUtils.success(bookService.insertBook(addBookVO));
    }

    @PutMapping("/insertBatchBook")
    @ApiOperation(value = "批量添加书籍")
    @OperLog(thing = "批量添加书籍")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse addBook(@Valid @RequestBody List<AddBookVO> addBookVOs) {
        List<Book> books = new ArrayList<>();
        for (AddBookVO addBookVO : addBookVOs) {
            Book book = bookService.getOne(new LambdaQueryWrapper<Book>().eq(Book::getRfid, addBookVO.getRfid()));
            if (ObjectUtil.isNotEmpty(book)) {
                throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "此RFID已被绑定");
            }
            Book bookCopy = BeanUtil.copyProperties(addBookVO, Book.class);
            books.add(bookCopy);
        }
        return ResultUtils.success(bookService.saveBatch(books));
    }

    @PostMapping()
    @ApiOperation(value = "修改书籍")
    @OperLog(thing = "修改书籍")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse updateBook(@Valid @RequestBody UpdateBookVO updateBookVO) {
        Book book = bookService.getOne(new LambdaQueryWrapper<Book>().eq(Book::getRfid, updateBookVO.getRfid()));
        if (ObjectUtil.isNotEmpty(book) && !book.getRfid().equals(updateBookVO.getRfid())) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "此RFID已被绑定到书籍:" + book.getName());
        }
        Book book1 = bookService.getById(updateBookVO.getId());
        if (!book1.getState().equals(BookStatusEnum.THELIBRARY.getCode())) {
            throw new BusinessException(ErrorCode.FORBIDDEN, "书籍未在柜,请勿操作");
        }
        if (book1.getIsDeleted().equals(IsDeletedEnum.DELETED.getCode())) {
            throw new BusinessException(ErrorCode.FORBIDDEN, "书籍已被停用,请先启用");
        }
        return ResultUtils.success(bookService.updateBook(updateBookVO));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除书籍")
    @OperLog(thing = "删除书籍")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse delBook(@PathVariable("id") Long id) {
        Book book = bookService.getById(id);
        if (!book.getState().equals(BookStatusEnum.THELIBRARY.getCode())) {
            throw new BusinessException(ErrorCode.FORBIDDEN, "该书籍未在柜,不可操作");
        }
        return ResultUtils.success(bookService.updateById(new Book(id, IsDeletedEnum.DELETED.getCode())));
    }
}
